package com.cfuture08.eweb4j.orm.dao.config;

import java.io.File;

import com.cfuture08.eweb4j.cache.SingleBeanCache;
import com.cfuture08.eweb4j.config.CheckConfigBean;
import com.cfuture08.eweb4j.config.ConfigConstant;
import com.cfuture08.eweb4j.config.bean.ConfigBean;
import com.cfuture08.eweb4j.config.log.LogFactory;
import com.cfuture08.eweb4j.jdbc.ConnectionManager;
import com.cfuture08.eweb4j.orm.dao.config.bean.DAOConfigBean;
import com.cfuture08.util.BeanXMLUtil;
import com.cfuture08.util.FileUtil;
import com.cfuture08.util.LogUtil;
import com.cfuture08.util.StringUtil;

public class DAOConfig {
	public synchronized static String check() {
		String error = null;
		ConfigBean cb = (ConfigBean) SingleBeanCache
				.get(ConfigConstant.CONFIGBEAN_ID);
		if (cb != null) {
			File configFile = new File(StringUtil.uriDecoding(FileUtil
					.getRootDir(DAOConfig.class)
					+ cb.getOrm().getDbInfoXmlFile()));
			try {
				DAOConfigBean dcb = (DAOConfigBean) BeanXMLUtil
						.getBeanXMLReader(configFile).readOne();
				if (dcb == null) {
					error = "DAOConfig.class : 读取不了任何配置文件信息！已经重写了配置文件，请重新填写完整，然后启动框架。";
				} else {
					error = CheckConfigBean.check(dcb);
					if (error == null) {
						SingleBeanCache.add(DAOConfigConstant.DBINFO, dcb);
						SingleBeanCache.add(dcb.getClass(), dcb);
						String error2 = ConnectionManager.getInstance()
								.getConnection() == null ? "" : null;
						if (error2 != null) {
							error = error2;
						} else {
							// ------log-------
							String debug = ((ConfigBean) SingleBeanCache
									.get(ConfigConstant.CONFIGBEAN_ID))
									.getOrm().getDebug();
							String info = "ORM.DAO 组件启动配置文件验证通过，已将读取到的配置信息存入缓存;";
							if ("true".equals(debug) || "1".equals(debug)) {
								LogUtil.getLogger().debug(info);
								
							}
							LogFactory.getORMLogger().write(info);
							// ------log-------
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				try {
					// 保存为备份文件
					File tf = new File(configFile.getAbsolutePath() + ".back"
							+ StringUtil.getNowTime("_MMddHHmmss"));
					FileUtil.copy(configFile, tf);
					BeanXMLUtil.getBeanXMLWriter(configFile,
							DAOConfigBeanCreator.getDAOBean()).write();
					error = "DAOConfig.class : 配置文件读取错误，已重写。异常捕获：";
					LogFactory.getORMLogger().write(error);
					LogUtil.getLogger().error(error, e);
				} catch (Exception e1) {
					e1.printStackTrace();
					error = "DAOConfig.class : 无法重写配置文件！异常捕获: ";
					LogFactory.getORMLogger().write(error);
					LogUtil.getLogger().error(error, e1);
				}
			}
		}

		return error;
	}
}
